//
//  ABTestConfiguration.swift
//  SwiftCode
//
//  Created by yuhus on 2023/7/17.
//

import Foundation

public struct ABTestConfiguration: ABTestConfigurationProtocol {
  static var environment: ABTestEnviroment = .online
  
  static var local = LocalABTest.shared
  static var online: ABTestProvider?
  public static func register(_ provider: ABTestProvider) {
    self.online = provider
  }
  
  public var environment: ABTestEnviroment {
    get { Self.environment }
    set { Self.environment = newValue }
  }
  
  public var local: ABTestProvider {
    Self.local
  }
  
  public var online: ABTestProvider {
    guard let online = Self.online else {
      fatalError("必须调用 ABTestConfiguration.register(_: ABTestProvider) 方法")
    }
    return online
  }
}

public struct LocalABTest: ABTestProvider {
  public static let shared = LocalABTest()
  
  private let userDefaults = UserDefaults(suiteName: "com.meta.storage.abtest")
  
  private init() {}
  
  public func getABValue<T>(key: String, default: T) -> T where T: ABValue {
    guard let userDefaults else { return `default` }
    return userDefaults.object(forKey: key) as? T ?? `default`
  }
  
  public func setABValue<T>(key: String, value: T) -> Bool where T: ABValue {
    guard let userDefaults else { return false }
    userDefaults.set(value, forKey: key)
    return true
  }
}
